/* eslint-disable import/extensions */
/* eslint-disable no-plusplus */
/* eslint-disable prefer-destructuring */
import ElEditable from '@components/el-editable';
import tabs from '@components/tabs';
import {
  distinguishForOCR,
  selectSalesDate,
  orderCommonSaveOrder
} from '@api/m_mall_web_v1.js';
import { isObject } from 'lodash';
import { formatDate } from '@const/filter';
import TableUpload from '~/modules/table-upload';
import { PurchaseProductsListComponent } from '~/components/report-bills-management/distributor/purchase-products-list';
import * as CONSTS from './index.const';
import { IndexService } from './index.service';

const indexService = new IndexService();
export default {
  name: 'distributorReportAdd',
  components: {
    tabs,
    ElEditable,
    TableUpload,
    PurchaseProductsListComponent
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      ...CONSTS,
      invoiceSellerNameCopy: '',
      salesperson: '',
      buttonloading: false,
      salesDateTips: '',
      supplier_code: '',
      // saleId: '',
      // getSupplierCode: '',
      // salesDateMonth: '',
      type: {
        bus_model: '1',
        busFunction: '2'
      },
      // 用于提交的页面信息
      page_data: {
        remark: '',
        contract: {},
        create: {
          supplier: '', // 供应商
          contract: '' // 合同
        }, // 创建报台
        sales_info: {
          target: '', // 销售对象
          date: '', // 销售日期
          salesDateMonth: ''
        }, // 销售信息
        sales_products: [], // 销售产品
        other_info: {
          additional: {}, // 附加信息
          invoice: {
            content: []
          }, // 发票信息
          other: {
            content: []
          } // 其他信息
        } // 其他信息
      },
      // 用于展示的数组列表或其他相关信息
      render_data: {
        rows_supplies: [],
        rows_sales_target: [],
        payload_contracts: {},
        extend_module: [],
        sales_info_rules: {
          target: [
            {
              required: true,
              message: '销售对象必选',
              trigger: 'blur'
            }
          ],
          salesDateMonth: [
            {
              required: true,
              message: '销售月必选',
              trigger: 'blur'
            }
          ],
          date: [
            {
              required: true,
              message: '销售日必选',
              trigger: 'blur'
            }
          ]
        }
      },
      data_store: {
        base_extend_data: []
      },
      // 页面用到的状态数据，比如tab切换，加载loading
      status_store: {
        active_tab: 0,
        loading: {
          contract: false,
          invoice: false
        },
        dateDisabled: true,
        dialog: {
          confirm: false
        },
        salesDate: {
          start: null,
          end: null
        }
      },
      pickerOptions: {
        disabledDate: time => {
          if (
            !this.status_store.salesDate.start &&
            !this.status_store.salesDate.end
          ) {
            return false;
          }
          return (
            this.status_store.salesDate.start > time.getTime() ||
            time.getTime() > this.status_store.salesDate.end
          );
        }
      },
      dayPickerOptions: {
        disabledDate: time =>
          this.page_data.sales_info.salesDateMonth > time.getTime()
      },
      // eslint-disable-next-line no-misleading-character-class
      reg: /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[A9|AE]\u3030|\uA9|\uAE|\u3030/gi,
      rules: {
        url: [{ required: true, message: '发票电子版', trigger: 'blur' }],
        invoiceCode: [{ required: true, message: '发票代码', trigger: 'blur' }],
        invoiceNum: [{ required: true, message: '发票号', trigger: 'blur' }],
        invoiceTittle: [
          { required: true, message: '发票抬头', trigger: 'blur' }
        ],
        invoiceAmount: [
          { required: true, message: '发票金额', trigger: 'blur' }
        ],
        invoiceDate: [{ required: true, message: '开票日期', trigger: 'blur' }]
      },
      ruleIndex: 0
    };
  },
  created() {
    this.newspaperEndDateMap = {};
    this.getSuppliers();
    this.initGlobalBtn();
  },
  methods: {
    // 切换“其他信息”的tab
    handleTab(index) {
      this.status_store.active_tab = index;
    },
    onSelectMonthChange(v) {
      if (v) {
        const month = new Date(v).getMonth() + 1;
        const obj = this.newspaperEndDateMap[month];
        // eslint-disable-next-line no-unused-expressions
        obj &&
          (this.salesDateTips = `${month}月份报台将在${obj.month}月${obj.day}号截止`);
      } else {
        this.salesDateTips = '';
      }
      this.page_data.sales_info.date = '';
      const arr = [];
      for (let i = 1; i <= 31; i++) {
        if (i < 10) {
          arr.push(`${v}-0${i}`);
        } else {
          arr.push(`${v}-${i}`);
        }
      }
      this.dayPickerOptions = {
        disabledDate: time =>
          arr.indexOf(formatDate(time.getTime(), 'YYYY-MM-DD')) < 0 ||
          time.getTime() > this.status_store.salesDate.end
      };
    },
    // 切换经销商
    onChangeSupplier(val) {
      this.supplier_code = val;
      // console.log(this.supplier_code, '175------');
      if (val) {
        this.onLoadContractData({
          number: 1,
          size: 20
        });
        // 当重新获取合同列表时，手动清空合同绑定的值
        this.page_data.contract = '';
        // 清空合同数组
        this.render_data.payload_contracts = {};
        // 清空销售对象、销售日期的绑定值
        this.clearAssociatedFileds();
        // 清空销售产品已选数据
        this.page_data.sales_products = [];
      }
    },
    // 切换合同
    onChangeContract(val) {
      if (this.validateContractExist()) {
        // 给page_data设置静态的产品线名称字段，以使添加销售产品可以使用
        const curProductLineName = this.render_data.payload_contracts.content.find(
          item =>
            val.productLineCode === item.productLineCode &&
            val.businessModelCode === item.businessModelCode &&
            val.marketCode === item.marketCode
        ).productLineName;
        this.page_data.create.contract = val.productLineCode;
        // this.getSupplierCode = val.supplierCode
        this.$set(this.page_data, 'curProductLineName', curProductLineName);
        this.setExpandData();
        this.getSalesDataRange();
        this.setSalesTargetOps();
        // 切换时，清空销售对象和销售日期的绑定值
        this.clearAssociatedFileds();
        // 清空选择的产品数据
        this.page_data.sales_products = [];
      }
    },
    clearAssociatedFileds() {
      this.page_data.sales_info.target = '';
      this.page_data.sales_info.date = '';
      this.page_data.sales_info.salesDateMonth = '';
      this.salesDateTips = '';
      // 清空校验
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    setSalesTargetOps() {
      const seledContract = this.render_data.payload_contracts.content.find(
        item => item === this.page_data.contract
      );
      this.render_data.rows_sales_target = seledContract.hospList;
    },
    // selectEvents() {
    //   this.getSalespersonList()
    // },
    // 合同数据加载
    async onLoadContractData(pager) {
      this.status_store.loading.contract = true;
      const result = await this.apiMMallWeb
        .ContractOrderV1ApiPOST({
          query: {
            page: pager.number,
            pageSize: pager.size,
            supplierCode: this.page_data.create.supplier,
            busModel: this.type.bus_model
          }
        })
        .finally(() => {
          this.status_store.loading.contract = false;
        });
      this.render_data.payload_contracts = result;
    },
    // 获取销售员数据列表
    // getSalespersonList() {
    //   const params = {
    //     hospitalCode: this.page_data.sales_info.target,
    //     supplierCode: this.getSupplierCode
    //   }
    //   this.$axios.$post(selectSaleManList, params)
    //   .then(res => {
    //     let result = this.data_store.base_extend_data;
    //     res.payload.map(item => {
    //       item.value = item.saleId
    //       item.label = item.saleName
    //     })
    //     result.forEach(item => {
    //       if(item.attributeName === '销售员' || item.attributeName === '销售代表' || item.attributeName === '原厂销售姓名' || item.attributeName === '销售') {
    //         item.valueRange = JSON.stringify(res.payload)
    //         this.page_data.other_info.additional[item.attributeNameValue] = res.payload[0].value;
    //         this.saleId = res.payload[0].saleId
    //       }
    //     })
    //     this.render_data.extend_module = indexService.getFormContent(result, this.ATTRIBUTE_TYPE_OPTIONS);
    //   })
    // },
    // 获取经销商列表
    async getSuppliers() {
      const supplies = await this.apiMMallWeb.SupplierOrderV1ApiPOST({
        query: {
          busModel: this.type.bus_model,
          page: 1,
          size: 1000
        }
      });
      this.render_data.rows_supplies = supplies.content || [];
    },
    // 获取并设置附加信息
    async setExpandData() {
      const originalFactory = this.render_data.payload_contracts.content.find(
        item => this.page_data.contract === item
      );
      const result = await this.apiMMallWeb.GetAppendInfoOrderV1ApiPOST({
        query: {
          busModel: '4',
          ddbm: 'WHOLESALE_ISSUE',
          productLineCode: this.page_data.contract.productLineCode,
          vendorNum: originalFactory.supplierCode,
          page: 1,
          pageSize: 9999
        }
      });
      // 这个数据后面提交接口的时候需要用到
      this.data_store.base_extend_data = result;
      this.render_data.extend_module = indexService.getFormContent(
        result,
        this.ATTRIBUTE_TYPE_OPTIONS
      );
      if (!this.render_data.extend_module.length) return;
      // 获取默认值
      const defaultValue = {};
      result.forEach(item => {
        defaultValue[item.attributeNameValue] = item.defaultValue;
      });
      // 如果存在>=一个默认值，那么就调用更新数据接口，触发校验。
      // 如果一个默认值都没有，那么就不调用更新数据接口，不触发校验
      if (!Object.values(defaultValue).some(item => item)) return;
      this.$nextTick(() => {
        this.$refs.expandFormRenderer.updateForm(defaultValue);
      });
    },
    // 删除一行发票信息
    removeCurInvoiceItem(scope) {
      this.$confirm('确定要删除该发票信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.page_data.other_info.invoice.content.splice(scope.$index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 删除一行其他附件
    removeCurOtherItem(scope) {
      this.$confirm('确定要删除该附件文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.page_data.other_info.other.content.splice(scope.$index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    addInvoiceItemValidate() {
      const content = this.page_data.other_info.invoice.content;
      if (content.length < 1) {
        this.addInvoiceItem();
      } else {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.addInvoiceItem();
          }
        });
      }
    },
    // 增加一行发票信息
    addInvoiceItem() {
      // 独立验证一下长度
      const maxLen = this.page_data.other_info.invoice.content.length;
      if (maxLen >= 50) {
        this.$message({
          type: 'warning',
          message: '发票信息最多可以添加50行！'
        });
        return;
      }
      // 判断一下，如果最新一行的数据没有添加，不允许添加下一行
      // if (!this.verifyCurFileItemDataComplete('invoice')) {
      //   this.$message({
      //     type: 'warning',
      //     message: '请将信息填写完整后再添加'
      //   });
      //   return;
      // }

      // 之前的校验如果没通过是不会走到这里的，懒一点的话可以不用在该方法内部校验是否填写
      // 但是，如果想要独立性更强一点，还是需要校验完备的。
      // 这里为啥是非，就不用说了吧
      if (!this.verifyCurFileItemLength().flag) {
        this.$message({
          type: 'warning',
          message: this.verifyCurFileItemLength().message
        });
        return;
      }

      const staticInvoiceItemData = {
        fileName: '', // 文件名 string
        fileType: '', // 文件后缀名 string：JPG、PDF等
        invoiceAmount: '', // 发票金额	number
        invoiceCode: '', // 发票代码 string
        invoiceDate: '', // 开票日期 string
        invoiceNum: '', // 发票号	string
        invoiceSellerName: '', // 开票方
        invoiceCheckCode: '', // 校验码
        invoiceTittle: '', // 发票抬头 string
        url: '' // 发票url	string
      };

      this.page_data.other_info.invoice.content.unshift(staticInvoiceItemData);
    },
    // 增加一行其他附件
    addOtherFileItem() {
      // 其实这里可以把验证逻辑再解藕，不过也都还好
      // 独立验证一下长度
      const maxLen = this.page_data.other_info.other.content.length;
      if (maxLen >= 50) {
        this.$message({
          type: 'warning',
          message: '其他附件最多可以添加50行！'
        });
        return;
      }
      // 验证如果当前行没有添加文件，则不允许再加一行
      if (!this.verifyCurFileItemDataComplete('other')) {
        this.$message({
          type: 'warning',
          message: '请将信息填写完整后再添加'
        });
        return;
      }
      const staticOtherItemData = {
        fileName: '', // 文件名	string
        fileType: '', // 文件后缀名：JPG、PDF等	string
        fileUrl: '' // 文件url	string
      };
      this.page_data.other_info.other.content.unshift(staticOtherItemData);
    },
    // 验证发票信息中，对应字段的长度
    verifyCurFileItemLength() {
      // let curData ;
      let len = null;
      len = this.page_data.other_info.invoice.content.length;
      // curData = this.page_data.other_info['invoice'].content[0];
      const status = {
        flag: true,
        message: ''
      };
      if (len === 0) {
        return status;
      }
      // if (curData.invoiceCode && curData.invoiceCode.length !== 12) {
      //   status.flag = false;
      //   status.message = '发票代码必须为12位';
      //   return status;
      // }
      // if (curData.invoiceNum && curData.invoiceNum.length !== 8) {
      //   status.flag = false;
      //   status.message = '发票号必须为8位';
      //   return status;
      // }
      return status;
    },
    verifyCurFileItemDataComplete(type) {
      // let curData = null;
      // let len = null;
      const len = this.page_data.other_info[type].content.length;
      if (len === 0) {
        return true;
      }
      let curData = this.page_data.other_info[type].content[0];

      if (type === 'invoice') {
        curData = JSON.parse(JSON.stringify(curData));
        delete curData.invoiceCheckCode;
        delete curData.invoiceSellerName;
      }
      const values = Object.values(curData);
      const flag = values.every(item => !!item);
      return flag;
    },
    // 发票附件地址回调
    returnInvoiceFileUrl(url, index, name) {
      this.page_data.other_info.invoice.content[index].url = url;
      if (!url) return;
      this.setInvoiceFiledsByFile(url, index, name);
    },
    // 其他附件地址回调
    returnOtherFileUrl(url, index, name) {
      this.page_data.other_info.other.content[index].fileUrl = url;
      this.page_data.other_info.other.content[index].fileName = name.split(
        '.'
      )[0];
      this.page_data.other_info.other.content[index].fileType = name.split(
        '.'
      )[1];
    },
    // 根据发票文件获取其他发票信息
    setInvoiceFiledsByFile(url, index, name) {
      this.status_store.loading.invoice = true;
      this.$axios({
        method: 'post',
        url: distinguishForOCR,
        data: {
          imgUrl: url
        }
      })
        .then(res => {
          const result = isObject(res.data.payload) ? res.data.payload : {};
          this.page_data.other_info.invoice.content[index].invoiceCode =
            result.invoiceCode;
          this.page_data.other_info.invoice.content[index].invoiceNum =
            result.quantity;
          this.page_data.other_info.invoice.content[index].invoiceSellerName =
            result.invoiceSellerName;
          this.page_data.other_info.invoice.content[index].invoiceCheckCode =
            result.invoiceCheckCode;
          this.page_data.other_info.invoice.content[index].invoiceTittle =
            result.invoiceTitle;
          this.page_data.other_info.invoice.content[index].invoiceAmount =
            result.totalAmount;
          this.page_data.other_info.invoice.content[index].invoiceDate =
            result.invoiceDate;
          this.page_data.other_info.invoice.content[
            index
          ].fileName = name.split('.')[0];
          this.page_data.other_info.invoice.content[
            index
          ].fileType = name.split('.')[1];
        })
        .finally(() => {
          this.status_store.loading.invoice = false;
        });
    },
    initGlobalBtn() {
      const btnObj = {
        type: 'btn',
        arr: []
      };
      const submitBtn = {
        type: 'primary',
        val: '提交',
        handle: this.checkRuleForm
      };
      btnObj.arr.push(submitBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    checkRuleForm(val) {
      const invoiceCount = this.page_data.other_info.invoice.content.length;
      if (invoiceCount <= 0) {
        this.showConfirmDialog();
        return;
      }
      this.ruleIndex = val || 0;
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.ruleIndex, invoiceCount);
          if (this.ruleIndex < invoiceCount) {
            this.ruleIndex++;
            if (this.ruleIndex === invoiceCount) {
              this.ruleIndex = 0;
              this.showConfirmDialog();
            } else {
              this.$nextTick(() => {
                this.checkRuleForm(this.ruleIndex);
              });
            }
          } else {
            this.$message.info('请把发票信息填写完整');
            this.ruleIndex = 0;
          }
        } else {
          this.$message.info('请把发票信息填写完整');
          this.ruleIndex = 0;
        }
      });
    },
    showConfirmDialog() {
      if (this.verfifySubmitData().pass) {
        // this.status_store.dialog.confirm = true;
        if (this.data_store.base_extend_data.length) {
          this.$refs.expandFormRenderer.validate(valid => {
            if (valid) {
              this.status_store.dialog.confirm = true;
            } else {
              this.$message({
                message: '您所填写的附加信息有误，请确认后重新填写',
                type: 'warning'
              });
            }
          });
        } else {
          this.status_store.dialog.confirm = true;
        }
      } else {
        this.$message({
          type: 'warning',
          message: this.verfifySubmitData().message
        });
      }
    },
    verfifySubmitData() {
      let result = {};
      const formData = this.page_data;
      const rules = [
        {
          rule: !!formData.create.supplier,
          message: '请选择供应商'
        },
        {
          rule: !!formData.create.contract,
          message: '请选择合同'
        },
        {
          rule: !!formData.sales_info.target,
          message: '请选择销售对象'
        },
        {
          rule: !!formData.sales_info.date,
          message: '请选择销售日期'
        },
        {
          rule: !!formData.sales_products.length,
          message: '请选择销售产品'
        },
        {
          rule: this.verifyCurFileItemDataComplete('invoice'),
          message: '请把发票信息填写完整'
        },
        {
          rule: this.verifyCurFileItemDataComplete('other'),
          message: '请把其他附件填写完整'
        },
        {
          rule: this.verifyCurFileItemLength().flag,
          message: this.verifyCurFileItemLength().message
        }
      ];
      result = this.checkRule(rules);
      return result;
    },
    checkRule(verifyRules) {
      const result = {
        pass: true,
        message: ''
      };
      for (let i = 0; i < verifyRules.length; i++) {
        const element = verifyRules[i];
        if (element.rule === true) {
          result.pass = true;
        } else {
          result.message = element.message;
          result.pass = false;
          return result;
        }
      }
      return result;
    },
    restructorSubmitData() {
      const finallyResult = {};
      const seledSupplierItem = this.render_data.rows_supplies.find(
        item => item.vendorCode === this.page_data.create.supplier
      );
      const seledContractItem = this.render_data.payload_contracts.content.find(
        item => item.productLineCode === this.page_data.create.contract
      );
      const commitAppendData = this.data_store.base_extend_data;
      commitAppendData.forEach(item => {
        const newItem = item;
        newItem.attributeValue =
          this.page_data.other_info.additional[item.attributeNameValue] || '';
        if (item.valueRange && item.attributeValue) {
          newItem.selectName = JSON.parse(item.valueRange).find(
            it => it.label === item.attributeValue
          ).label;
        }
      });
      finallyResult.busModel = this.type.bus_model;
      finallyResult.busFunction = this.type.busFunction;
      finallyResult.supplierVo = seledSupplierItem;
      finallyResult.contractVo = seledContractItem;
      finallyResult.remark = this.page_data.remark;
      // finallyResult.saleId	 = this.saleId;
      finallyResult.saleDate = new Date(
        this.page_data.sales_info.date
      ).getTime();
      finallyResult.saleTargetCode = this.page_data.sales_info.target;
      finallyResult.saleTargetName = this.render_data.rows_sales_target.find(
        item => item.hospitalCode === this.page_data.sales_info.target
      ).hospitalName;
      finallyResult.saveProductVO = this.page_data.sales_products;
      finallyResult.saveProductVO.forEach(item => {
        const newItem = item;
        newItem.productUnitName = item.productUnit;
        newItem.attribute1 = item.specs;
      });
      finallyResult.orderAppendPOS = commitAppendData; // 附加信息
      finallyResult.commonFileForms = this.page_data.other_info.other.content; // 其他附件
      finallyResult.orderInvoiceForms = this.page_data.other_info.invoice.content; // 发票信息
      // 给发票信息增加serialNumber序号字段
      finallyResult.orderInvoiceForms.forEach((item, index) => {
        const newItem = item;
        newItem.serialNumber = finallyResult.orderInvoiceForms.length - index;
      });
      return finallyResult;
    },
    submitFinalData() {
      this.buttonloading = true;
      this.$axios({
        url: orderCommonSaveOrder,
        method: 'post',
        data: this.restructorSubmitData()
      })
        .then(res => {
          if (res.data.code === '0') {
            this.$router.go(-1);
            this.$message({
              type: 'success',
              message: '提交成功'
            });
          }
        })
        .catch(() => {
          this.$message({
            type: 'warning',
            message: '提交失败'
          });
        })
        .finally(() => {
          this.status_store.dialog.confirm = false;
          this.buttonloading = false;
        });
    },
    validateContractExist() {
      if (this.page_data.contract === '') {
        this.status_store.dateDisabled = true;
      } else {
        this.status_store.dateDisabled = false;
      }
      return !this.status_store.dateDisabled;
    },
    getSalesDataRange() {
      const originalFactory = this.render_data.payload_contracts.content.find(
        item => this.page_data.contract === item
      );
      this.$axios({
        method: 'post',
        url: selectSalesDate,
        data: {
          originalFactoryCode: originalFactory.supplierCode,
          page: 0,
          pageSize: 0,
          productLineCode: this.page_data.contract.productLineCode
        }
      }).then(res => {
        const startDate = res.data.payload.newspaperStartDate || '';
        const endDate = res.data.payload.newspaperEndDate || '';
        this.status_store.salesDate.start = startDate
          ? new Date(startDate).getTime() - 24 * 60 * 60 * 1000
          : '';
        this.status_store.salesDate.end = endDate
          ? new Date(endDate).getTime()
          : '';
        this.newspaperEndDateMap = res.data.payload.newspaperEndDateMap || {};
        // console.log(res.data.payload.newspaperEndDateMap, "<")
      });
    }
  }
};
